﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace A2DFramework.ServiceLocatorService.Configuration
{
    public static class LocatorServiceConfiguration
    {
        public static List<Service> Services { get; set; }

        static LocatorServiceConfiguration()
        {
            Load();
        }

        public static void ReLoad()
        {
            Load();
        }

        private static void Load()
        {
            //load setings from xml file
            XElement root = XElement.Load(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "A2D.config"));

            root = root.Element("ServiceLocator");
            if (root == null)
                throw new Exception("ServiceLocator node not exists");

            //判断是否存在configSource属性，存在则从指定的路径中加载服务配置信息
            //比如从网络共享路径中加载，这样如果分布较多，则可以降低配置的工作量以及减少出错概率
            if (root.Attribute("configSource") != null)
            {
                string configSource = root.Attribute("configSource").Value;

                string filePath = string.Empty;

                if (File.Exists(configSource))
                    filePath = configSource;
                else
                    filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configSource);

                root = XElement.Load(filePath);
                root = root.Element("ServiceLocator");
            }

            var srvList = new List<Service>();
            foreach (var serviceElm in root.Elements("Service"))
            {
                Service srv = new Service();

                srv.ContractNamespace = serviceElm.Attribute("ContractNamespace").Value;
                srv.Contract = serviceElm.Attribute("Contract").Value;
                srv.AssemblyPath = serviceElm.Attribute("AssemblyPath").Value;

                foreach (var urlElm in serviceElm.Elements("Url"))
                {
                    Url url = new Url();

                    url.EndpointType = (EndpointType)Enum.Parse(typeof(EndpointType), urlElm.Attribute("EndpointType").Value);

                    if (urlElm.Attribute("Version") != null)
                        url.Version = urlElm.Attribute("Version").Value;

                    url.ReferenceUrl = urlElm.Value;

                    srv.Urls.Add(url);
                }

                srvList.Add(srv);
            }

            Services = srvList;
            ServiceLocator.ClearCache();
        }
    }
}
